import axios from 'axios'
import { useRouter } from 'vue-router'

// const baseURL = 'http://8.149.132.213:8080';
const baseURL = 'http://localhost:8080'

const instance = axios.create({
  baseURL,
  timeout: 5000,
})

// 全局设置 Token 请求头的方法
export const setAuthToken = (token: string) => {
  instance.defaults.headers.common['Authorization'] = `Bearer ${token}`
}

export const login = async (account: string, password: string) => {
  try {
    const response = await instance.post('/api/user/login', { account, password })
    console.log(response.data)

    // 确保正确存储用户ID和完整信息
    localStorage.setItem('userId', response.data.id)

    return response.data
  } catch (error) {
    clearAuthTokens() // 登录失败时清除可能的旧token
    if (axios.isAxiosError(error)) {
      // 优先使用后端返回的详细错误信息
      const backendError = error.response?.data
      let errorMessage = '登录失败'

      if (backendError?.message) {
        errorMessage = backendError.message
      } else if (error.response?.status === 401) {
        errorMessage = '账号或密码错误'
      }

      throw new Error(errorMessage)
    }
    throw new Error('网络错误，请检查您的连接')
  }
}

export function registerUser(account: string, username: string, password: string): Promise<any> {
  return instance.post('/api/user/register', {
    account,
    username,
    password,
  })
}

// 验证Token有效性
export const validateToken = async (token: string) => {
  try {
    // 先设置Token到请求头
    setAuthToken(token)

    console.log('[validateToken] 发送验证请求，token:', token.substring(0, 20) + '...')
    const response = await instance.post('/api/user/validate-token', { token })
    console.log('[validateToken] 验证响应:', response.data)
    return response.data
  } catch (error) {
    if (axios.isAxiosError(error)) {
      const status = error.response?.status
      const data = error.response?.data

      console.error(`[validateToken] 错误详情: status=${status}, data=`, data)

      if (status === 400) {
        throw new Error('Token不能为空')
      }
    }
    throw new Error('Token 验证失败')
  }
}

// 获取用户详情
export const getUserDetail = async (id: number) => {
  try {
    const token = localStorage.getItem('token') || sessionStorage.getItem('token')
    if (token) {
      instance.defaults.headers.common['Authorization'] = `Bearer ${token}`
    }

    const response = await instance.get(`/api/user/${id}`)
    return response.data
  } catch (error) {
    if (axios.isAxiosError(error)) {
      const backendError = error.response?.data
      let errorMessage = '[getUserDetail] 获取用户详情失败'

      const status = error.response?.status
      const router = useRouter()

      // 强制处理 403 错误
      if (status === 403) {
        clearAuthTokens()
        console.warn('[getUserDetail] 403 错误')
        ElMessage({
          message: '会话异常！请重新登录',
          type: 'error',
          duration: 5000,
          showClose: true,
        })
        throw new Error('非法操作')
      }

      if (backendError?.message) {
        errorMessage = backendError.message
      } else if (error.response?.status === 404) {
        errorMessage = '用户不存在'
      }

      throw new Error(errorMessage)
    }
    throw new Error('网络错误，请检查您的连接')
  }
}
/**
 * 获取用户的全部记账记录（优化版）
 * @param {number} userId - 用户ID
 * @returns {Promise<Array<BookData>>} - 记账记录列表
 */
export const getBookDataList = async (userId: number) => {
  try {
    const response = await instance.get<BookData[]>('/api/book/list', {
      params: { userId },
    })

    if (Array.isArray(response.data)) {
      return response.data.map((item) => {
        return {
          ...item,
          bookDate: formatDate(item.bookDate),
          formattedPrice: formatCurrency(item.price),
          // 关键修复：确保type=1为支出，type=0为收入
          transactionType: item.type === 1 ? '支出' : '收入',
          typeColor: item.type === 1 ? 'danger' : 'success',
        }
      })
    } else {
      throw new Error('接口返回数据格式异常，非数组类型')
    }
  } catch (error: any) {
    console.error('[getBookDataList] 错误:', error.message)
    ElMessage.error(error.message || '获取记账记录失败，请稍后再试')
    throw error
  }
}
/**
 * 删除账单记录
 * @param {number} id - 账单ID
 * @returns {Promise<boolean>} - 删除是否成功
 */
export const deleteBookRecord = async (id: number): Promise<boolean> => {
  try {
    // 获取 token 并设置
    const token = localStorage.getItem('token') || sessionStorage.getItem('token')
    if (token) setAuthToken(token)

    console.log(`[deleteBookRecord] 发送删除请求，id: ${id}`)
    const response = await instance.delete(`/api/book/delete/${id}`) // 修正为正确路径

    if (response.status === 200 && response.data === '删除成功') {
      ElMessage.success('删除账单记录成功')
      return true
    } else {
      ElMessage.error('删除账单记录失败，请稍后再试')
      return false
    }
  } catch (error: any) {
    console.error('[deleteBookRecord] 错误:', error.message)

    if (axios.isAxiosError(error)) {
      const status = error.response?.status
      const data = error.response?.data

      if (status === 401) {
        ElMessage.error('登录状态失效，请重新登录')
        localStorage.clear()
        sessionStorage.clear()
        const router = useRouter()
        router.push('/login')
      } else {
        ElMessage.error(data?.message || '删除账单记录失败，请稍后再试')
      }
    } else {
      ElMessage.error('网络错误，请检查您的连接')
    }

    return false
  }
}

/**
 * 添加账单记录
 * @param {Object} formData - 账单数据
 * @param {number} formData.type - 类型（0收入，1支出）
 * @param {string} formData.bookDate - 日期时间（格式：yyyy-MM-dd HH:mm:ss）
 * @param {string} formData.category - 类别
 * @param {string} formData.price - 金额
 * @param {string} formData.remark - 备注
 * @param {number} formData.userId - 用户ID
 * @param {string} formData.source - 来源（默认值: 其它）
 * @returns {Promise<boolean>} - 添加是否成功
 */
export const addBookRecord = async (formData: {
  type: string
  bookDate: string
  category: string
  price: string
  remark: string
  userId: number
  source: string
}) => {
  try {
    // 获取 token 并设置
    const token = localStorage.getItem('token') || sessionStorage.getItem('token')
    if (token) setAuthToken(token)

    // 处理默认值
    const data = {
      ...formData,
      source: formData.source || '其它',
    }

    console.log('[addBookRecord] 发送添加请求', data)
    const response = await instance.post('/api/book/add', data)

    if (response.status === 200 && response.data === '添加成功') {
      ElMessage.success('添加账单记录成功')
      return true
    } else {
      ElMessage.error('添加账单记录失败，请稍后再试')
      return false
    }
  } catch (error) {
    console.error('[addBookRecord] 错误:', (error as any).message)

    if (axios.isAxiosError(error)) {
      const status = error.response?.status
      const data = error.response?.data

      if (status === 401) {
        ElMessage.error('登录状态失效，请重新登录')
        localStorage.clear()
        sessionStorage.clear()
        const router = useRouter()
        router.push('/login')
      } else {
        ElMessage.error(data?.message || '添加账单记录失败，请稍后再试')
      }
    } else {
      ElMessage.error('网络错误，请检查您的连接')
    }

    return false
  }
}

/**
 * 更新账单记录
 * @param {Object} formData - 账单数据
 * @param {number} formData.id - 账单ID
 * @param {string|number} formData.type - 类型（0收入，1支出）
 * @param {string} formData.bookDate - 日期时间（格式：yyyy-MM-ddTHH:mm:ss.SSSZ，ISO字符串）
 * @param {string} formData.category - 类别
 * @param {number|string} formData.price - 金额
 * @param {string} formData.remark - 备注
 * @param {number} formData.userId - 用户ID
 * @param {string} formData.source - 来源
 * @returns {Promise<boolean>} - 更新是否成功
 */
export const updateBookRecord = async (formData: {
  id: number
  type: string | number
  bookDate: string
  category: string
  price: number | string
  remark: string
  userId: number
  source: string
}): Promise<boolean> => {
  try {
    // 获取 token 并设置
    const token = localStorage.getItem('token') || sessionStorage.getItem('token')
    if (token) setAuthToken(token)

    // 兼容类型转换
    const data = {
      ...formData,
      type: typeof formData.type === 'string' ? formData.type : String(formData.type),
      price: typeof formData.price === 'number' ? formData.price : Number(formData.price),
      bookDate: formData.bookDate, // 需为ISO字符串
      source: formData.source || '其它',
    }

    console.log('[updateBookRecord] 发送更新请求', data)
    const response = await instance.put('/api/book/update', data)

    if (response.status === 200 && response.data === '修改成功') {
      ElMessage.success('账单修改成功')
      return true
    } else {
      ElMessage.error('账单修改失败，请稍后再试')
      return false
    }
  } catch (error) {
    console.error('[updateBookRecord] 错误:', (error as any).message)

    if (axios.isAxiosError(error)) {
      const status = error.response?.status
      const data = error.response?.data

      if (status === 401) {
        ElMessage.error('登录状态失效，请重新登录')
        localStorage.clear()
        sessionStorage.clear()
        const router = useRouter()
        router.push('/login')
      } else {
        ElMessage.error(data?.message || '账单修改失败，请稍后再试')
      }
    } else {
      ElMessage.error('网络错误，请检查您的连接')
    }

    return false
  }
}

/**
 * 更新用户信息
 * @param {number} id - 用户ID
 * @param {string} username - 新用户名
 * @returns {Promise<any>} - 更新后的用户信息
 */
export const updateUserInfo = async (id: number, username: string): Promise<any> => {
  try {
    // 获取 token 并设置
    const token = localStorage.getItem('token') || sessionStorage.getItem('token')
    if (token) setAuthToken(token)

    console.log(`[updateUserInfo] 发送更新请求，id: ${id}, username: ${username}`)
    const response = await instance.put('/api/user/update', {
      id,
      username,
    })

    if (response.status === 200) {
      ElMessage.success('用户信息更新成功')
      return response.data
    } else {
      ElMessage.error('用户信息更新失败，请稍后再试')
      return null
    }
  } catch (error: any) {
    console.error('[updateUserInfo] 错误:', error.message)

    if (axios.isAxiosError(error)) {
      const status = error.response?.status
      const data = error.response?.data

      if (status === 401) {
        ElMessage.error('登录状态失效，请重新登录')
        clearAuthTokens()
        const router = useRouter()
        router.push('/login')
      } else {
        ElMessage.error(data?.message || '用户信息更新失败，请稍后再试')
      }
    } else {
      ElMessage.error('网络错误，请检查您的连接')
    }

    return null
  }
}

/**
 * 修改密码
 * @param {number} userId - 用户ID
 * @param {string} oldPassword - 原密码
 * @param {string} newPassword - 新密码
 * @returns {Promise<boolean>} - 修改是否成功
 */
export const changePassword = async (userId: number, oldPassword: string, newPassword: string): Promise<boolean> => {
  try {
    // 获取 token 并设置
    const token = localStorage.getItem('token') || sessionStorage.getItem('token')
    if (token) setAuthToken(token)

    console.log(`[changePassword] 发送修改密码请求，userId: ${userId}`)
    const response = await instance.put('/api/user/changePassword', {
      userId,
      oldPassword,
      newPassword,
    })

    if (response.status === 200 && response.data.code === 200) {
      ElMessage.success('密码修改成功')
      return true
    } else {
      ElMessage.error('密码修改失败，请稍后再试')
      return false
    }
  } catch (error: any) {
    console.error('[changePassword] 错误:', error.message)

    if (axios.isAxiosError(error)) {
      const status = error.response?.status
      const data = error.response?.data

      if (status === 401) {
        ElMessage.error('登录状态失效，请重新登录')
        clearAuthTokens()
        const router = useRouter()
        router.push('/login')
      } else {
        ElMessage.error(data?.message || '密码修改失败，请稍后再试')
      }
    } else {
      ElMessage.error('网络错误，请检查您的连接')
    }

    return false
  }
}

// 日期格式化函数
function formatDate(isoDate: string): string {
  if (!isoDate) return '未知日期'
  try {
    const date = new Date(isoDate)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
  } catch (e) {
    console.error('日期格式化失败:', e)
    return isoDate
  }
}

// 金额格式化函数
function formatCurrency(amount: number): string {
  return `¥${amount.toFixed(2)}`
}

// 定义记账数据类型（可单独提取到types.ts）
interface BookData {
  id: number
  type: number // 1:支出 0:收入
  bookDate: string
  category: string
  price: number
  remark: string
  source: string
}
// 清除token的辅助函数
export const clearAuthTokens = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('rememberMe')
  localStorage.removeItem('account')
  localStorage.removeItem('username')
  sessionStorage.removeItem('token')
  sessionStorage.removeItem('username')
  // 清除请求头
  delete instance.defaults.headers.common['Authorization']
}
